<template>
<label :class="{'is-invalid-label': errors.has(name)}">{{ label }}
  <field-error v-show="errors.has(name)" :err="errors.first(name)" />
  <ul :class="['et-list', {'is-invalid-input': errors.has(name)}]">
    <li style="display: none"><!-- fix the first item always checked issue of click black space -->
      <label v-if="type === 'multiple'" class="et-checkbox">
        <input type="checkbox" />
        <span></span>
      </label>
      <label v-if="type === 'single'" class="et-radio">
        <input type="radio" />
        <span></span>
      </label>
    </li>
    <li v-for="(item, idx) in items" :key="idx">
      <div class="grid-x">

        <div class="cell small-10">

          <label v-if="type === 'multiple'" class="et-checkbox">
            <input type="checkbox" :name="name" :value="item.val" :checked="item.checked" v-model="selected" v-validate="rules" />
            <span></span>
          </label>
          <label v-if="type === 'single'" class="et-radio">
            <input type="radio" :name="name" :value="item.val" :checked="item.checked" v-model="selected" v-validate="rules" />
            <span></span>
          </label>

          <a v-if="itemHandler" @click="() => { itemHandler(item); }">{{ item.txt }}</a>
          <span v-if="!itemHandler">{{ item.txt }}</span>

        </div>

        <div class="cell small-2 text-center">
          <slot :item="item"></slot>
        </div>

      </div>
    </li>
  </ul>
</label>
</template>

<script>
import FieldError from './FieldError';

export default {

  components: {
    FieldError
  },

  props: {
    items: {
      type: Array,
      default() {
        return [];
      }
    },
    name: {
      type: String,
      required: true
    },
    label: {
      type: String,
      required: true
    },
    itemHandler: {
      type: Function
    },
    type: {
      type: String,
      validator(value) {
        return ['single', 'multiple'].indexOf(value) !== -1;
      }
    },
    rules: {
      type: Object,
      default() { return {}; }
    }
  },

  inject: ['$validator'],

  data() {
    return {
      selected: []
    };
  },

  watch: {
    selected() {
      this.$emit('select', {
        key: this.name,
        val: this.selected.length === 0 ? null : this.selected
      });
    },
    items() {
      this.selected = [];
      this.items.forEach((item) => {
        if (item.checked) {
          this.selected.push(item.val);
        }
      });
    }
  },

  methods: {
    reset() {
      this.selected = [];
    }
  }
};
</script>
